package com.shop.user.api.controller;

import com.shop.common.entity.user.UserBase;
import com.shop.common.tmpl.BaseController;
import com.shop.common.util.RandomValidateCodeUtil;
import com.shop.common.util.state.ResultCode;
import com.shop.common.util.SessionUtils;
import com.shop.user.api.model.UserBaseModel;
import com.shop.user.atom.atomsvc.IUserAtomSvc;
import com.shop.user.conf.util.MapEnum;
import com.shop.common.util.RedisUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@RestController
@RequestMapping("/user/")
@CrossOrigin
public class UserLoginController extends BaseController {
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    SessionUtils sessionUtils;
    @Autowired
    IUserAtomSvc userService;

    private final static Logger logger = LoggerFactory.getLogger(UserLoginController.class);

    @PostMapping("userLogin")
    public String userLogin(@RequestBody UserBaseModel userModel, HttpServletRequest request) {
        String account = userModel.getAccount();
        String password = userModel.getPassword();
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password)) {
            return returnFailed("用户名或密码不能为空");
        }
        String verCode = userModel.getVerCode();
        if (userModel.getVerCode() != null) {
            String redisKey = request.getHeader("VERCODETOKEN");
            if (!redisUtil.exists(redisKey)) {
                return returnFailed("验证码错误或已过期");
            }
            String realVerCode = redisUtil.get(redisKey);
            if (realVerCode == null || "".equals(realVerCode) || !realVerCode.equals(verCode)) {
                return returnFailed("验证码错误或已过期");
            }
            UserBase userBase = userService.selectBaseUserByAccountMapping(account);
            if (userBase == null) {
                return returnFailed("该账号不存在");
            }
            if (userBase.getStatus() == -1 || userBase.getStatus() == -2) {
                return returnFailed("该账号已注销");
            }
            password = DigestUtils.md5Hex(password);
            if (!password.equals(userBase.getPassword())) {
                return returnFailed("用户密码错误");
            }
            Map<String, Object> resultMap = new HashMap<>();
            HttpSession session = request.getSession();
            String token = session.getId();
            resultMap.put("AUTHTOKEN", token);
            resultMap.put("NICKNAME", userBase.getNickname() );
            resultMap.put("STATUS", userBase.getStatus() );
            resultMap.put("SCHOOL",userBase.getSchoolId());
            sessionUtils.SET_USER(userBase, token);
            return returnJSON(ResultCode.SUCCESS.value(), "", resultMap);
        } else {
            return returnFailed("验证码错误或已过期");
        }
    }

    @GetMapping("getVerify")
    public String getVerify() {
        try {
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            Map<String, String> codeMap = randomValidateCode.getRandcode();//输出验证码图片方法
            String code = codeMap.get("code");
            String codeToken = UUID.randomUUID().toString();
            redisUtil.set(codeToken, code,60*5);
            codeMap.put("token", codeToken);
            return returnJSON(ResultCode.SUCCESS.value(), "", codeMap);
        } catch (Exception e) {
            logger.error("获取验证码失败 ", e);
        }
        return returnFailed();
    }

    public Map<String, Object> getLoginToken(UsernamePasswordToken token) {
        Subject subject = SecurityUtils.getSubject();
        Map<String, Object> map = MapEnum.HashMap.crateObjectMap();
        try {
            subject.login(token);
            map.put("token", subject.getSession().getId());
            System.out.println("登录成功");
        } catch (IncorrectCredentialsException e) {
            map.put("error", "密码错误");
//            System.out.println("密码错误");
        } catch (LockedAccountException e) {
            map.put("error", "账号已锁定");
//            System.out.println("登录失败，账号已锁定");
        } catch (AuthenticationException e) {
            map.put("error", "该用户不存在");
//            System.out.println("该用户不存在");
        } catch (Exception e) {
            map.put("error", "登陆失败");
            e.printStackTrace();
        }
        return map;
    }


}
